package com.xinbochuang.machine.admin.controller.common;

import cn.hutool.core.lang.UUID;
import com.wf.captcha.SpecCaptcha;
import com.xinbochuang.machine.common.constant.Constants;
import com.xinbochuang.machine.common.redis.RedisCache;
import com.xinbochuang.machine.framework.web.domain.AjaxResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author 黄晓鹏
 * @date 2020-09-09 10:19
 */
@RestController
public class CaptchaController {

    @Resource
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode() {
        // 保存验证码信息
        String uuid = UUID.randomUUID().toString();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        // 生成验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        String code = specCaptcha.text().toLowerCase();

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        Map<String, Object> data = new HashMap<>();
        data.put("uuid", uuid);
        data.put("img", specCaptcha.toBase64());
        return AjaxResult.data(data);
    }

}
